<?php

namespace addons\mental\controller;

use app\admin\model\video\Order;
use app\admin\model\consult\Order as ConsultOrder;
use app\admin\model\xlzxinfo\Xlzxinfo;
use app\admin\model\xlzxinfo\Package;
use app\common\model\WxTui;
use think\addons\Controller;
use think\Exception;
use think\Log;
use think\Config;


class Callback extends Controller
{

    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                 Log::write('微信支付回调');
                 Log::write(json_encode($data,true));
                 Log::info($data);
                if ($paytype == 'alipay') {
                    $trade_no = $data['trade_no'];
                }else{
                    $trade_no = $data['transaction_id'];
                }

                if ($data['attach']=='mental'){

                    $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                    \addons\mental\model\Order::settle($data['out_trade_no'], $payamount,'',$trade_no,$paytype);

                }elseif ($data['attach']=='video'){

                    $videoOrderModel = new Order();
                    $order = $videoOrderModel->where(['order_id'=>$data['out_trade_no']])->find();
//                    Log::info('订单信息');
//                    Log::info($order);
                    if ($order['status'] != 'paid') {
                        //更新订单
                        $order->status = 'paid';
                        $order->paytime = time();
                        $order->paytype = $paytype;
                        $order->save();
                        //分佣
                        Order::VideoCommission($order['order_id']);
                    }
                }elseif ($data['attach']=='consult'){
                    $ConsultOrderModel = new ConsultOrder();
                    $order = $ConsultOrderModel->where(['id'=>$data['out_trade_no']])->find();
                    if ($order['status'] != 'paid') {
                        //更新订单
                        $now = datetime(time());
                        // 订单有效期  3天
                        if($order['is_package']==0){
                            $day_time = Config::get('site.effective_day') * 24 * 60 * 60;
                        }
                        // 套餐单独的有效期  3个月
                        if($order['is_package']>0){
                            $package_info = Package::get($order['is_package']);
                            $day_time = $package_info['package_expiration_month']* 30 * 24 * 60 * 60;
                        }

                        $effective_time = strtotime($now)+$day_time;
                        //更新订单
                        $order->pay_status = 'paid';
                        $order->pay_time = $now;
                        $order->effective_time = $effective_time;
                        $order->pay_type = $paytype;
//                        $order->server_start_time = $now;
                        $order->save();
                        //\app\admin\model\consult\Order::ConsultCommission($order['id']);
                        //预约订单给老师发送公众号模板消息
                        \addons\mental\model\WxUser::push_template_order($order['id']);
//                        if ($order['type']==2){
//                            $xlzxinfo = Xlzxinfo::where(['id'=>$order['xlzxinfo_id']])->find();
//                            $touser = \app\common\model\User::where('id',$xlzxinfo['user_id'])->find();
//                            $response = WxTui::sendMessage2($touser['openid'],$order['id'],$order['start_time']);
//                            Log::info($response);
//                        }
                    }
                }


                
            } catch (Exception $e) {
                Log::write($e->getMessage(), 'pay_log');
            }
            echo $pay->success();
        } else {
            /* $pay = \addons\epay\library\Service::checkReturn($paytype);
            if (!$pay) {
                $this->error('签名错误');
            }          */
        }
        return;
    }

    /**
     * @ DateTime 2022-02-26
     * @ 头条担保交易支付回调
     * @return void
     */
    public function ttPay()
    {
        $echostr = $this->request->param('echostr');
        $signature = $this->request->param('signature');
        $timestamp = $this->request->param('timestamp');
        $msg = html_entity_decode($this->request->param('msg'));
        $nonce = $this->request->param('nonce');
        if (!$echostr || !$signature || !$timestamp || !$nonce) {
            exit;
        }
        $config = get_addon_config('mental');
        $token = $config['tt_pay_token'];
        $tmpArr = [$token, $timestamp, $nonce, $msg];
        sort($tmpArr, SORT_STRING);
        $str = implode($tmpArr);

        if (sha1($str) != $signature) {
            exit;
        }
        if ($this->request->method() == 'GET') {
            echo $echostr;
            exit;
        }
        $data = (array)json_decode($msg, true);
        if (isset($data['cp_orderno']) && isset($data['total_amount'])) {
            \addons\mental\model\Order::settle($data['cp_orderno'], $data['total_amount'] / 100);
            echo json_encode([
                "err_no" => 0,
                "err_tips" => "success"
            ]);
            exit;
        }
    }


}
